# !/usr/bin/python
# -*- coding: UTF-8 -*-
import logging
import os
from logging import FileHandler
from datetime import datetime
import json
from .config import base_log_path
from logging.handlers import TimedRotatingFileHandler
import re

def train_log_config():
    # 创建log日志目录
    if not os.path.exists("./log"):
        os.makedirs("./log")

    logger = logging.getLogger(__name__)

    logger.handlers.clear()

    format_data = "%(asctime)s - %(name)s - %(levelname)s - %(message)s"
    log_path = os.path.join("./log", "log")
    error_path = os.path.join("./log", "runtime-error.log")

    # 设置日志记录等级
    logger.setLevel(logging.INFO)

    # 工作日志
    file_handler = TimedRotatingFileHandler(
        filename=log_path, when="MIDNIGHT", interval=1, backupCount=30, encoding="utf-8"
    )
    # 报错日志
    file_error_log = logging.FileHandler(error_path)
    file_error_log.setLevel(level=logging.ERROR)
    file_error_log.setFormatter(logging.Formatter(format_data))

    # 控制台日志
    console_handler = logging.StreamHandler()
    console_handler.setLevel(logging.INFO)
    console_handler.setFormatter(logging.Formatter(format_data))

    file_handler.suffix = "%Y-%m-%d.log"
    file_handler.extMatch = re.compile(r"^\d{4}-\d{2}-\d{2}.log$")
    file_handler.setFormatter(logging.Formatter(format_data))

    # 将所有handler添加到logger
    logger.addHandler(file_handler)
    logger.addHandler(file_error_log)
    logger.addHandler(console_handler)

    return logger


def log_config():
    # 创建log日志目录
    if not os.path.exists(base_log_path):
        os.makedirs(base_log_path)

    logger = logging.getLogger(__name__)
    # 防止日志重复打印，每次创建handler时先清空handler
    logger.handlers.clear()

    format_data = "%(message)s"
    log_path = os.path.join(base_log_path, f"modellog.{datetime.now().strftime('%Y-%m-%d')}.json.log")
    # applog.model.${YYYYMMDD}.json.log
    # 设置日志记录等级
    logger.setLevel(logging.INFO)

    # 工作日志
    file_handler = FileHandler(
        filename=log_path, encoding="utf-8"
    )

    file_handler.setFormatter(logging.Formatter(format_data))
    logger.addHandler(file_handler)

    return logger


# 用于 大模型平台部署的日志函数
def log_record(status, type, content, log_obj):
    my_dict = {
        "status": status,
        "log_time": datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f'),
        "type": type,
        "content": content,
    }
    my_dict.update(log_obj)
    LOGGER = log_config()
    LOGGER.info(json.dumps(my_dict,ensure_ascii=False))
